package com.gxwzxy.medic.dao.Impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.gxwzxy.medic.dao.RoleDao;
import com.gxwzxy.medic.entity.Role;
import com.gxwzxy.medic.entity.otherentity.RoleMenu;
import com.gxwzxy.medic.until.Connect;

public class RoleDaoImpl implements RoleDao {

	// 声明连接变量
	Connection conn = null;
	ResultSet rs = null;
	PreparedStatement ps = null;
	
	/**
	 * 查询所有角色
	 */
	@Override
	public List<Role> findRole() {
		//声明变量
		String sql = null;
		ArrayList<Role> ar = new ArrayList<Role>();
		try {
			//给sql赋值
			sql = "select * from role";
			//调用静态方法
			rs = Connect.executeF(sql);
			//遍历结果
			while(rs.next()) {
				Role r = new Role(rs.getInt(1),rs.getString(2),rs.getString(3));
				ar.add(r);
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			Connect.close(conn , ps , rs);
		}
		return ar;
	}

	/**
	 * 根据Id删除角色
	 */
	@Override
	public boolean RoleDelete(String roleId) {
		//声明变量
		String sql = null;
		String rsql = null;
		int i = 0;
		int j = 0;
		sql = "delete from role where role_id = ?";
		i = Connect.executeDML(sql, roleId);
		rsql = "delete from role_menu where role_id = ?";
		j = Connect.executeDML(rsql, roleId);
		if(i!=0&&j!=0) {
			return true;
		}else {
			return false;
		}
	}

	/**
	 * 添加角色
	 */
	@Override
	public boolean addRole(Role role, String[] menuId) {
		//声明变量
		String sql = null;
		String msql = null;
		int i = 0;
		int j = 0;
		//获取连接
		conn = Connect.getConnection();
		try {
			//关闭事务自动提交
			conn.setAutoCommit(false);
			//创建sql
			sql = "insert into role(role_id,role_name) value(?,?)";
			msql = "insert into role_menu(role_id,menu_id)value(?,?)";
			//创建sql执行对象
			ps = conn.prepareStatement(sql);
			//对占位符赋值
			ps.setString(1, role.getRoleId());
			ps.setString(2, role.getRoleName());
			//执行sql
			i =ps.executeUpdate();
			for(int m = 0;m<menuId.length;m++) {
				ps = conn.prepareStatement(msql);
				ps.setString(1, role.getRoleId());
				ps.setString(2, menuId[m]);
				j = ps.executeUpdate();
			}
			//提交事务
			conn.commit();
		}catch(Exception e) {
			e.printStackTrace();
			try {
				conn.rollback();
			}catch(Exception e1) {
				e1.printStackTrace();
			}
		}finally {
			Connect.closedouble(conn, ps);
		}
		if(i>0&&j>0) {
			return true;
		}else {
			return false;
		}
	}

	/**
	 * 根据roleId修改角色表
	 */
	@Override
	public boolean updateRoleByroleId(String roleId,String roleName) {
		String sql = "update role set role_name = ? where role_id = ?";
		int i = Connect.executeDML(sql, roleName,roleId);
		if(i!=-1) {
			return true;
		}else {
			return false;
		}
	}

}
